<template>
  <!--材料月结修改 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="月结明细"
          name="receivingMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
               <BillTop title="材料月结编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    label-width="150px"
                    :rules="rules"
                    ref="basicFormData"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="月结编号：">
                          {{ basicFormData.billNo }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="机构：">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="年度：">
                          {{basicFormData.year}}

                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item
                          label="月结日期："
                        >
                        {{basicFormData.monthlySettlementDate}}
                          <!-- <el-date-picker
                            v-model="basicFormData.monthlySettlementDate"
                            type="datetime"
                            placeholder="选择日期时间">
                          </el-date-picker> -->
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="月份：" >
                          {{basicFormData.month}}

                        </el-form-item>
                      </el-col>
                       <el-col :span="12">
                        <el-form-item label="月结区间：">
                          <span>{{basicFormData.startTime +'-'+ basicFormData.endTime}}</span>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="状态：">
                          {{ "草稿" }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>

            <!-- ------------------------------------------------------------------------------------- -->
          </div>

          <!-- 月结明细 -->
          <div id="receivingMaterialsCon" class="con">
            <div class="tabs-title" id="receivingMaterials">月结明细</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      @click="Add"
                      >月结</el-button
                    >
                  </div>
                </div>
              </div>
              <el-table
                :data="materialCloseList"
                border
                style="width: 100%"
                @cell-mouse-enter="cellMouseEnter"
                @cell-mouse-leave="cellMouseLeave"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                 ref="table"
                v-sortTable="{ 'tableData': materialCloseList, '_this': this, 'ref': 'table' }"
              >
                <el-table-column
                  fixed
                  type="index"
                  label="序号"
                  width="80"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="materialClassName"
                  label="物资类别"
                  min-width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="materialName"
                  label="物资名称"
                  min-width="100"
                >
                </el-table-column>
                <el-table-column prop="spec" label="规格" width="100">
                </el-table-column>
                <el-table-column prop="texture" label="材质" width="100">
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                </el-table-column>
                <el-table-column prop="quantity" label="月结数量" width="100">
                </el-table-column>
                <el-table-column
                  prop="price"
                  label="成本单价（元）"
                  width="120"
                >
                </el-table-column>
                <el-table-column
                  prop="amount"
                  label="金额（元）"
                  width="130"
                >
                </el-table-column>
                <el-table-column
                  prop="consumedQuantity"
                  label="已消耗数量"
                  width="130"
                >
                </el-table-column>

              </el-table>
            </div>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <el-button
        type="primary"
        style="background: #2e61d7"
        @click="save('basicFormData')"
        >保存</el-button
      >
      <el-button
        type="primary"
        style="background: #2e61d7"
        @click="submit('basicFormData')"
        >保存并提交</el-button
      >
      <el-button type="danger" size="small" @click="ctDelete">删除</el-button>
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
// import CommonApi from '@/api/materials/common.js'
import Api from '@/api/materials/materialClose.js'
import { getUuid, formatDate } from '@/utils/common'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            materialCloseList: [], //明细
            auditHistoryTable: [], //审核历史
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'billNo': '',
                'endTime': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isFirst': true,
                'month': 0,
                'monthlySettlementDate': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'startTime': '',
                'state': '',
                'workId': '',
                'year': 0
            },
            objFlag: {
                flag5: false,
            },
            monthList: [
                {
                    value: '1',
                    label: '1',
                },
                {
                    value: '2',
                    label: '2',
                },
                {
                    value: '3',
                    label: '3',
                },
                {
                    value: '4',
                    label: '4',
                },
                {
                    value: '5',
                    label: '5',
                },
                {
                    value: '6',
                    label: '6',
                },
                {
                    value: '7',
                    label: '7',
                },
                {
                    value: '8',
                    label: '8',
                },
                {
                    value: '9',
                    label: '9',
                },
                {
                    value: '10',
                    label: '10',
                },
                {
                    value: '11',
                    label: '11',
                },
                {
                    value: '12',
                    label: '12',
                },
            ],
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            orgIds: '',
            //验证
            rules: {
                monthlySettlementDate: [
                    { required: true, message: '请选择月结日期', trigger: 'change' },
                ],
                year: [{ required: true, message: '请选择年度', trigger: 'change' }],
                month: [{ required: true, message: '请选择月份', trigger: 'change' }],
            },
        }
    },
    computed: {
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
    },
    components: {
        AttachComp,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.billid = this.$route.query.billid
        this.getBasicData() //进入页面就获取基本信息数据
        this.getBasicDataList()
        this.getAttach()
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        if (this.$route.query.name) {
            setTimeout(() => {
                this.onChangeTab({
                    name: this.$route.query.name,
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //计算成本单价  成本金额/月结数量
        calculationPrice () {
            let num = 0
            this.monthList.forEach(a=>{
                a.children.forEach(item=>{
                    item.price = Number(item.amount) / Number(item.quantity)
                    // item.consumedQuantity
                    num += Number(item.price)
                    item.consumedQuantity = num //计算月结数量消耗累计，物资消耗后反写更新。
                })
            })
        },
        //检查是否有未审核完的相关数据
        checkUnAuditData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/checkUnAuditData',
                    params: {
                        month: this.basicFormData.month,
                        orgId: this.orgId,
                        year: parseInt (this.basicFormData.year),
                    },
                })
        },
        //新增月结
        Add () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/initDtls',
                    params: {
                        month: this.basicFormData.month,
                        orgId: this.orgId,
                        year: Number (this.basicFormData.year),
                    },
                }).then(val=>{
                    this.materialCloseList = []
                    const mapObj = {}
                    let arr = []
                    val.forEach(item=>{
                        item.children.forEach(e=>{
                            const children = []
                            let obj
                            const topClassId = item.topClassId
                            const topClassName = item.topClassName
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: null,
                                    totalQuantity: null,
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                               	'amount': e.amount, //金额
                                'billId': this.billid, //材料月结id
                                'changeType': 1,
                                'consumedQuantity': e.consumedQuantity, //已消耗数量
                                'dtlId': '', //材料月结明细id
                                'materialClassId': e.materialClassId, //物资类别id
                                'materialClassName': e.materialClassName, //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'price': e.price, //单价
                                'quantity': e.quantity, //数量
                                'spec': e.spec, //规格型号
                                'texture': e.texture, //材质
                                'unit': e.unit//计量单位
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })

                    })
                    this.materialCloseList = arr
                    this.calculationPrice()
                })
        },
        //保存
        save (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.$Ajax
                        .httpGet({
                            url: '/material/monthlySettlement/checkUnAuditData',
                            params: {
                                month: this.basicFormData.month,
                                orgId: this.orgId,
                                year: this.basicFormData.year
                            },
                        }).then(res=>{
                            console.log('res', res.code)
                            if( res.code === 200) {
                                this.basicFormData.monthlySettlementDate =   formatDate(this.basicFormData.monthlySettlementDate, 'yyyy-MM-dd hh:mm:ss')
                                if(this.basicFormData.startTime == '/') {
                                    this.basicFormData.startTime = ''
                                }
                                this.basicFormData.month = parseInt(this.basicFormData.month)
                                //基础信息
                                const p1 = Api.EditMaterialClose(this.basicFormData)
                                //明细
                                const p2 = Api.EditMaterialCloseList(this.materialCloseList)
                                Promise.all([p1, p2]).then(() => {
                                    this.clientPop('suc', '保存成功！', ()=>{
                                        this.getBasicData()
                                        this.getBasicDataList()
                                    })
                                })
                            }
                        })

                } else {
                    return false
                }
            })
        },
        //提交
        submit (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.basicFormData.monthlySettlementDate =   formatDate(this.basicFormData.monthlySettlementDate, 'yyyy-MM-dd hh:mm:ss')
                    this.monthlySettlementDates = (Date.parse(new Date(this.basicFormData.monthlySettlementDate)) + 86400000 * 7)
                    this.monthlySettlementDates = formatDate(this.monthlySettlementDates, 'yyyy-MM-dd hh:mm:ss')
                    this.basicFormData.month = parseInt(this.basicFormData.month)
                    this.$Ajax
                        .httpGet({
                            url: '/material/monthlySettlement/checkUnAuditData',
                            params: {
                                month: this.basicFormData.month,
                                orgId: this.orgId,
                                year: this.basicFormData.year
                            },
                        }).then(res=>{
                            if( res.code === 200) {
                                if(this.basicFormData.startTime == '/') {
                                    this.basicFormData.startTime = ''
                                }
                                //基础信息
                                const p1 = Api.EditMaterialClose(this.basicFormData)
                                //明细
                                const p2 = Api.EditMaterialCloseList(this.materialCloseList)
                                //提交
                                const p3 = this.commit()
                                Promise.all([p1, p2, p3]).then(() => {
                                    let info = `保存并提交成功！月结消耗数据有效期为${this.basicFormData.monthlySettlementDate}时间至${this.monthlySettlementDates}时间，如果需要做物资消耗请在该时间段完成，否则只能在下次月结后做物资消耗`
                                    this.clientPop('suc', info, this.cancel())
                                })
                            }
                        })
                } else {
                    return false
                }
            })
        },

        commit () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/commit',
                    params: {
                        billid: this.billid
                    },
                })
        },
        //根据消耗盘点id查询消耗盘点基础信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    console.log('res', res)
                    this.basicFormData = res
                    this.basicFormData.year = this.basicFormData.year.toString()
                    if(this.basicFormData.startTime == null || this.basicFormData.startTime == '') {
                        this.basicFormData.startTime  = '/'
                    }
                })
        },
        //根据消耗盘点id获取消耗盘点明细信息
        getBasicDataList () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    console.log('res', res)
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })
                    this.materialCloseList = res
                })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthlySettlement/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel)
                    }
                })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./materialClose')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>